<template>
  <div class="container" id="goods-edit">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="">
        <el-breadcrumb-item>
          <div class="div1">商品管理</div>
        </el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/goodsList' }" >
          <div class="div1">商品列表</div>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <div class="div2">{{ breadcrumbTitle }}</div>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 面包屑导航 -->
    <!-- 查询 -->
    <div class="content page-title">
      <h2>商品信息</h2>
    </div>
    <div class="content">
      <h3>基础信息</h3>
      <el-form :model="infoForm" :rules="infoRules" ref="infoForm" label-width="100px" class="info-form">
        <el-form-item label="商品分类">
          <div class="goods-category-edit">
            <span>{{categoryArrStr}}</span>
            <span class="edit-btn" @click="toOtherPages('goodsCategoryEdit')" v-if="currentPageStatus == 'add'">编辑</span>
          </div>
        </el-form-item>
        <el-form-item label="商品类型" prop="goodsType">
          <el-radio-group v-model="infoForm.goodsType" :disabled="currentPageStatus !== 'add'">
            <el-radio
              v-for="item in dictionaries.goods_type"
              :key="item.dictId"
              :value="item.dictId"
              :label="item.dictName"
              :name="item.dictId"
            ></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="infoForm.name" placeholder="请输入商品名称" maxlength="30" show-word-limit clearable></el-input>
        </el-form-item>
        <el-form-item label="商品编码" v-if="infoForm.goodsNo" class="goods-no">
          <el-input v-model="infoForm.goodsNo" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="brandId" class="brand-id">
          <el-select
            v-model="infoForm.brandId"
            placeholder="请选择所属品牌"
            filterable
            clearable
          >
            <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="content attr">
      <div class="attr-title">类目属性</div>
      <div class="attr-content">
      <h4>商品属性</h4>
        <template v-for="(item, index) in goodsAttrData">
          <h5>{{ item.name }}</h5>
          <div class="attr-list">
            <form-filed :formconfig="item.formconfig" :formData="item.formData" @formDataval="dialogClick" :ref="'formAttr'+item.id"/>
          </div>
        </template>
        </div>
      </div>

    <div class="content image-text-form">
      <h3>图文信息</h3>
      <el-form label-width="100px">
        <el-form-item label="商品图片">
          <upload-picture :limit="5" :file-list="infoForm.imageList" @getUrl="getUrl" @handleRemove="handleRemove" />
<!--          <upload-picture></upload-picture>-->
        </el-form-item>
        <el-form-item label="商品详情">
          <!--          <editor :init="editorInit" v-model="infoForm.detail" api-key="70xmc76i21jyu8ob8fmf4dtcjfpz0atkne1ttkxppmzsu230"/>-->
          <!-- <tinymce v-model="infoForm.details"></tinymce> -->
          <quill-editor
            v-model="infoForm.details"
            ref="myQuillEditor"
            :options="editorOption"
            class="editor"
          ></quill-editor>
          <div class="bottom" style="display: none">
            <el-upload
              class="centerImg"
              :action="' '"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleAvatarChangeIcon"
              ref="uploadicon"
            >
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="content" id="sku-content">
      <h3>价格库存</h3>
      <div class="sku-box">
        <div class="sku-title"><i>*</i><span>商品规格</span></div>
        <div class="sku-content-box">
          <div class="goods-sale">
            <el-select
              v-model="goodsSaleDataListValue"
              v-if="currentPageStatus === 'add'"
              placeholder="请选择"
              multiple
              collapse-tags
              :multiple-limit="3"
              :disabled="currentPageStatus !== 'add'"
              @change="onChangeGoodsSaleDataListValue"
            >
              <el-option
                v-for="item in skuFormConfig.sourceAttribute"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <!-- <el-button type="primary">添加规格</el-button> -->
            <!-- <pre>{{skuFormConfig}}</pre> -->
            <div class="choose-attribute">
              <template v-for="(k, fatherIndex) in skuFormConfig.attribute" >
<!--                <h5>{{ k.name }}<span>（已选 {{ k.item.length }}）</span></h5>-->
                <h5>
                  <el-input size="small" v-model="k.name" @input="changeInput()" @blur="changeAttributeTitle(k.name, fatherIndex)" @focus="changeAttributeTitleFocus(k.name, fatherIndex)" placeholder="+ 自定义规格名称"></el-input>
                  <i class="el-icon-circle-close" @click="onDeleteContent(fatherIndex,childrenIndex, 'father')" v-if="currentPageStatus === 'add'"></i>
                  <hr>
                  <span>规格值</span>
                  <span>（已选 {{ k.item.length }}）</span>
                </h5>
                <div class="choose-attribute-list">
                  <!--
                  <el-tag
                      :key="tag"
                      v-for="tag in k.item"
                      closable
                      :disable-transitions="false"
                      @close="handleClose(tag)">
                    {{tag}}
                  </el-tag>
                  -->
                  <template v-for="(tag, childrenIndex) in k.item">
                      <template v-if="skuFormConfig.attribute[fatherIndex].itemList[childrenIndex]">
                        <el-input
                          size="small"
                          :key="childrenIndex"
                          v-model="skuFormConfig.attribute[fatherIndex].itemList[childrenIndex].content"
                          v-if="skuFormConfig.attribute[fatherIndex].itemList[childrenIndex].content"
                          @input="changeInput()"
                          @change="onChangeContent(fatherIndex,childrenIndex)"
                        >
                      </el-input><i class="el-icon-circle-close" @click="onDeleteContent(fatherIndex,childrenIndex)" v-if="currentPageStatus === 'add'"></i>
                    </template>
                  </template>
                  <el-input
                      class="input-new-tag"
                      v-model="skuFormConfig.inputValueArrTemp[fatherIndex]"
                      ref="saveTagInput"
                      size="small"
                      placeholder="+ 自定义规格值"
                      @keyup.enter.native="handleInputConfirm(fatherIndex)"
                      @blur="handleInputConfirm(fatherIndex)"
                      @focus="onFocus(fatherIndex)"
                      @input="changeInput()"
                  >
                    <el-button slot="append" icon="el-icon-check" type="primary" @click="handleInputConfirm(fatherIndex)"></el-button>
                  </el-input>
<!--                  <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 自定义规格值</el-button>-->
                </div>
              </template>
              <template v-if="skuFormConfig.attribute.length < 3">
              <h5 v-if="inputVisible"> <el-input size="small" v-model="specNameTemp.name" @input="changeInput()" placeholder="+ 自定义规格名称"></el-input> </h5>
              <div class="choose-attribute-list" v-if="inputVisible">
                <el-input
                    size="small"
                    placeholder="+ 自定义规格值"
                    v-model="specNameTemp.item"
                    @input="changeInput()"
                  >
                </el-input>
              </div>
              </template>
            </div>
            <template v-if="skuFormConfig.attribute.length < 3">
            <el-button type="primary" :disabled="skuFormConfig.attribute.length > 2" @click="showInput()" v-if="!inputVisible && currentPageStatus === 'add'">添加规格</el-button>
            <el-button type="primary" :disabled="skuFormConfig.attribute.length > 2" @click="addSpecName()" v-if="inputVisible">确认添加</el-button>
            </template>
          </div>
          <div class="goods-sale-list">
            <SkuForm
                ref="skuForm"
                :source-attribute="skuFormConfig.sourceAttribute"
                :attribute.sync="skuFormConfig.attribute"
                :sku.sync="skuFormConfig.sku"
                :disabled="skuFormConfig.showForm"
                :structure="skuFormConfig.structure"
                v-if="skuFormConfig.attribute.length !==0 "
            >
              <template #skuNo="slotSkuNo">
                {{slotSkuNo.row.skuNo ? slotSkuNo.row.skuNo : '- -'}}
              </template>
              <template #status="slotProps">
                <el-switch
                    v-model="slotProps.row.status"
                    active-value="1"
                    inactive-value="0"
                ></el-switch>
              </template>
            </SkuForm>
          </div>
<!--          <sku ref="sku" @change="changeSku" :th-list="thList" class="sku-table"></sku>-->
        </div>
      </div>
      <div v-if="infoForm.minPrice && infoForm.maxPrice"  class="market-price">
        <h3 class="max-min-price"><span>市场价</span><span>¥ {{ infoForm.minPrice }} - {{ infoForm.maxPrice }}</span>元</h3>
      </div>
      <!-- <pre>{{skuFormConfig.attribute}}</pre> -->
      <div class="status-box">
        <div class="list">是否上架</div>
        <el-radio-group v-model="infoForm.status" class="right">
          <el-radio
            v-for="item in dictionaries.sale_status"
            :key="item.dictId"
            :value="item.dictId"
            :label="item.dictName"
            :name="item.dictId"
          ></el-radio>
        </el-radio-group>
      </div>
    </div>
    <div class="content bottom-but">
      <el-button type="warning" @click="toOtherPages( 'goodsList' )">返回</el-button>
      <el-button type="primary" @click="verificationData" v-if="parArray.indexOf('eidt_chengbenjia') != -1">{{ submitButtonText }}</el-button>
    </div>
  </div>
</template>

<script>

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import Quill from 'quill'
import imageResize from 'quill-image-resize-module' // 引用
import { ImageDrop } from 'quill-image-drop-module'
Quill.register('modules/imageDrop', ImageDrop)
Quill.register('modules/imageResize', imageResize) // 注册

// import Tinymce from '@/components/Tinymce/index'
import uploadPicture from '@/components/upload/picture.vue'
// import sku from "./components/sku/index"
import formFiled from '@/components/form/index'
import SkuForm from 'vue-sku-form'
import mixinsGoodsEdit from './mixins/mixinsGoodsEdit.js'
import mixinsGoodsEditQuill from './mixins/mixinsGoodsEditQuill.js'

const checkNumber = (data, index, callback) => {
  const val = data[index].stock
  // console.log(typeof val === 'number', !isNaN(val))
  console.log(typeof val === 'number' && !isNaN(val))
  if (!isNaN(val)) {
    callback()
  }
  callback(new Error('填写有误'))
}
export default {
  components: {
    uploadPicture,
    formFiled,
    SkuForm,
    quillEditor
  },
  data () {
    return {
      currentPageStatus: 'add', // 当前页面状态 add 添加 ， edit 编辑
      breadcrumbTitle: '新增商品',
      maxSkuNo: 1, // 通过接口获取最大 skuNo
      formFiledDataState: true, // 类目属性 状态
      skuFormConfig: {
        sourceAttribute: [], // SKU可选属性
        attribute: [], // SKU已选属性，支持 .sync 修饰符
        structure: [ // 表单结构
          { name: 'marketPrice', type: 'input', label: '市场价(元)', batch: false, required: true,
            validate: (data, index, callback) => {
              console.log(data)
              const val = data[index].marketPrice
              if (!isNaN(val) && val > -1) {
                data[index].marketPrice = Number(data[index].marketPrice).toFixed(2)
                callback()
              }
              callback(new Error('填写有误'))
            }
          },
          { name: 'costPrice', type: 'input', label: '成本价(元)', batch: false, required: true,
            validate: (data, index, callback) => {
              const val = data[index].costPrice
              if (!isNaN(val) && val > -1) {
                data[index].costPrice = Number(data[index].costPrice).toFixed(2)
                callback()
              }
              callback(new Error('填写有误'))
            }
          },
          { name: 'retailPrice', type: 'input', label: '零售价(元)', batch: false, required: true,
            validate: (data, index, callback) => {
              const val = data[index].retailPrice
              if (!isNaN(val) && val > -1) {
                data[index].retailPrice = Number(data[index].retailPrice).toFixed(2)
                callback()
              }
              callback(new Error('填写有误'))
            }
          },
          { name: 'purchasePrice', type: 'input', label: '内购价格(元)', batch: false, required: true,
            validate: (data, index, callback) => {
              const val = data[index].purchasePrice
              if (!isNaN(val) && val > -1) {
                data[index].purchasePrice = Number(data[index].purchasePrice).toFixed(2)
                callback()
              }
              callback(new Error('填写有误'))
            }
          },
          { name: 'stock', type: 'input', label: '库存', batch: false, required: true,
            validate: (data, index, callback) => {
              const val = data[index].stock
              if (!isNaN(val) && val > -1) {
                data[index].stock = Number(data[index].stock).toFixed(0)
                callback()
              }
              callback(new Error('填写有误'))
            }
          },
          // { name: "skuNo", type: "input", label: "SKU编码", batch: false },
          { name: 'skuNo', type: 'slot', label: 'SKU编码', batch: false },
          {
            name: 'status',
            type: 'slot',
            defaultValue: '1',
            label: '上下架',
            tip: '单个 SKU 上架和下架状态！'
          }
        ],
        sku: [], // SKU数据，支持 .sync 修饰符
        theme: 2, // SKU选择栏主题风格，可选1或2
        showForm: true, // 是否显示SKU选择栏  false 显示 true 隐藏
        inputValueArr: [],
        inputValueArrTemp: []
      },
      submitButtonText: '发布商品', // 提交按钮方案
      infoForm: { // 基础信息
        categoryId: '', //	是	int	类目id （数据来源：接口 - /order/comm/commodityCategory/commList）
        goodsType: '', //	是	string	商品类型（字典：goods_type）
        name: '', //	是	string	商品名称
        brandId: '', //	是	int	品牌id（数据来源：接口 - /order/comm/brand/commList?pageNo=1&pageSize=999）
        attrList: '', //	是	Object[]	商品属性组列表
        // imageList: [{url: "http://fenxiao.muruji.com/internalSystem/76c19d4d-5a0e-4ff2-9b4f-239040be1d58"}], //	是	Object[]	图片列表
        imageList: [], //	是	Object[]	图片列表
        details: '', //	否	string	详情
        specList: [], //	是	Object[]	规格列表
        skuList: [], //	是	Object[]	sku列表
        status: '', //	是	string	状态（字典分组：enable_status）
        goodsNo: '', // 商品编号
        maxPrice: '', // 最高价
        minPrice: '', // 最低价
        submitButtonText: '发布商品' // 提交按钮方案
      },
      infoRules: { // 基础验证
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        brandId: [
          { required: true, message: '请选择品牌', trigger: 'change' }
        ],
        goodsType: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
      },
      categoryIdArr: [], // 获取路由 categoryId
      categoryArrStr: '', // 回显 category
      goodsAttrDataList: [], // 类目商品属性库列表
      goodsSaleDataList: [], // 类目的销售属性列表
      goodsSaleDataListValue: [],
      goodsAttrData: [{
        formconfig: {},
        formData: {}
      }],
      formFiledData: {}, // 表单组件数 商品属性组列表
      currentStatus: 100, // 当前列表状态
      categoryList: [], // 目类列表
      brandList: [], // 品牌
      dialog: { visible: false, title: '编辑', type: '' },
      selectionId: [], // 选 中 id
      parArray: [] // 按钮权限
    }
  },
  mixins: [mixinsGoodsEdit, mixinsGoodsEditQuill],
  // mounted () { this.addQuillTitle() },
  created () {
    this.initialization() // 初始化 信息
    this.getButtonTreeDto() // 获取权限设定
  },
  watch: {
    skuFormConfig: {
      handler (newVal, oldVal) {
        // console.log(newName, oldName)
        const arr = []
        newVal.sku.forEach(item => {
          arr.push(item.marketPrice)
        })
        const sortArr = arr.sort(function (a, b) { return a - b })
        // console.log(sortArr)
        this.infoForm.maxPrice = sortArr[sortArr.length - 1] // 最高价
        this.infoForm.minPrice = sortArr[0] // 最低价
      },
      deep: true // 为true，表示深度监听，这时候就能监测到a值变化
    },
    goodsSaleDataListValue (a, b) {
      console.log(a, b)
      if (this.skuFormConfig.attribute.length > 3) {
        this.$message({
          message: '规格最多只有三条',
          type: 'warning'
        })
        this.onChangeGoodsSaleDataListValue(b)
      }
    }
  },
  computed: {},
  methods: {
    getButtonTreeDto () {
      // 获取权限设定
      this.limits = JSON.parse(sessionStorage.getItem('limit'))
      const params = this.limits.buttonTreeDto.filter(
          (item) => item.menuCode === 'goodsList'
      )
      params[0].buttonList.forEach((item) => {
        this.parArray.push(item.code)
      })

      // 查看成本价权限
      console.log('查看成本价权限', this.parArray.indexOf('eidt_chengbenjia'), this.parArray.indexOf('eidt_chengbenjia') != -1, this.parArray)
      if( this.parArray.indexOf('eidt_chengbenjia') === -1){
        this.skuFormConfig.structure.forEach((item, index) => {
          if( item.name === 'costPrice'){
            this.skuFormConfig.structure.splice(index,1)
          }
        })
      }
    },
    // 接受表单组件的数据
    dialogClick (val, state) {
      console.log(val, state)
      this.formFiledDataState = state
      this.formFiledData = Object.assign(this.formFiledData, val)
      // console.log(this.formFiledData,'接受表单组件的数据');
    },
    // 初始化 信息
    initialization () {
      const queryObj = this.$route.query
      let category
      // 判断是否有 商品 ID 和 TYPE 类型 双从判断 当前页面状态
      // 获取商品信息 - 编辑模式
      if (queryObj.id && queryObj.type === 'edit') {
        // console.log(queryObj)
        this.getGoodInfo(queryObj.id)
        this.currentPageStatus = 'edit'
        this.submitButtonText = '修改商品'

      } else {
        // 添加模式
        if (queryObj && queryObj.category) { category = this.$route.query.category }
        if (category && category.length !== 0) {
          this.infoForm.categoryId = category[category.length - 1]
          this.categoryIdArr = category
          this.getCategoryList(category) // 获取 目类 列表
          // 获取 类目商品属性库列表 并 还原 展示 商品属性 表单
          this.getDataList(category[category.length - 1])
          this.getGoodsSaleDataList(category[category.length - 1]) // 查询指定类目的销售属性
          this.getBrandList(category[category.length - 1]) // 获取 品牌 列表
          // 初始化 上 下架 状态 , 为了等待数据返回添加一个 setTimeout
          setTimeout(() => {
            // 设置 商品类型、 是否上架 默认值
            if (this.dictionaries.goods_type.length !== 0) { this.infoForm.goodsType = this.dictionaries.goods_type[0].dictName }
            if (this.dictionaries.sale_status.length !== 0) { this.infoForm.status = this.dictionaries.sale_status[1].dictName }
          }, 1000)
        } else {
          console.log('还没选择商品分类')
          this.$alert('还没选择商品分类', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              console.log(action)
              this.toOtherPages('goodsCategoryEdit')
            }
          })
        }
      }
    },
    // 获取 商品信息
    getGoodInfo (goodsId) {
      this.breadcrumbTitle = '编辑商品'
      const params = { id: goodsId }
      this.$api.goodsDetail(params).then((res) => {
        const categoryId = res.data.categoryInfo.id
        this.infoForm = Object.assign(this.infoForm, res.data)
        this.infoForm.brandId = res.data.brandId.toString()
        // 回显类目ID
        this.infoForm.categoryId = categoryId
        /*
        this.infoForm.imageList.forEach(item => {
          if (item.url && item.url.indexOf('http://fenxiao.muruji.com/') !== 0) { item.url = this.ImgHttps + item.url }
        })
        */
        setTimeout(() => {
          // 回显 商品类型
          if (this.dictionaries.goods_type.length !== 0) {
            const goodsTypeObj = this.dictionaries.goods_type.find(e => { return e.dictId === this.infoForm.goodsType })
            if (goodsTypeObj) { this.infoForm.goodsType = goodsTypeObj.dictName }
          }
          // 回显 上架 与 下架状态
          if (this.dictionaries.sale_status.length !== 0) {
            const statusObj = this.dictionaries.sale_status.find(e => { return e.dictId === this.infoForm.status.toString() })
            if (statusObj) { this.infoForm.status = statusObj.dictName }
          }
        }, 1000)
        // 获取 类目商品属性库列表 并 还原 展示 商品属性 表单
        this.getDataList(categoryId, res.data.attrGroupList)
        this.getCategoryList(categoryId, res.data.categoryInfoList)
        this.getBrandList(categoryId) // 获取 品牌 列表
        this.getSkuNo(goodsId) // 生成sku编码
        // 查询指定类目的销售属性
        this.getGoodsSaleDataList(categoryId, res.data.specList, res.data.skuList)
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取类目列表
    getCategoryList (categoryInfo, categoryInfoList) {
      // console.log(categoryInfo)
      const params = { pageNo: 1, pageSize: 999 }
      this.$api.categoryList(params).then((res) => {
        this.categoryList = res.data.list
        this.onChangeEditClassId(categoryInfo, categoryInfoList)
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取 类目商品属性库列表 并 还原 展示 商品属性 表单
    getDataList (categoryId, attrGroupList) {
      const params = { categoryId }
      this.$api.goodsAttrDataList(params).then((res) => {
        const resData = res.data
        const arr = []
        // debugger
        resData.forEach(firstItem => {
          const obj = {
            name: firstItem.name,
            id: firstItem.id,
            // 表单宽度  表单的list 表单的匹配规则
            formconfig: { labeWidth: 100, itemList: [], rules: {}},
            // 表单提交数据，注：如果类型是checkbox，必须foemData里边提前声明数组
            formData: {}
          }
          firstItem.itemList.forEach(secondItem => {
            // 字典 goods_attr_type
            // 1、文本 2、单选  3、多选  4、时间
            const type = Number(secondItem.typeFlag)
            let propId
            /*
            // 修改模式下，需要多添加一个 ID
            if(this.currentPageStatus == "edit"){
              attrGroupList.forEach( aItem => {
                aItem.itemList.forEach( aItemList => {
                  if(aItem.id == firstItem.id && aItemList.id == secondItem.id){
                    propId = `value-${firstItem.id}-${secondItem.id}-${aItemList.id}`;
                  }
                })
              })
            } else {
              propId = `value-${firstItem.id}-${secondItem.id}`;
            }
            */
            propId = `value-${firstItem.id}-${secondItem.id}`
            switch (type) {
              case 1: // 文本
                obj.formconfig.itemList.push({ type: 'input', prop: propId, placeholder: '请输入内容', label: secondItem.name })
                obj.formconfig.rules = Object.assign(obj.formconfig.rules, { [propId]: [{ required: secondItem.requiredFlag != 0, message: '请输入内容', trigger: 'blur' }] })
                break
              case 2: // 单选
                const radiosArr = []
                /*
              secondItem.itemList.forEach( radiosItem => { radiosArr.push({label:radiosItem.label,value:radiosItem.id}) })
              obj.formconfig.itemList.push( { type:'radio', prop:propId, label:secondItem.name, radios:radiosArr } )
              obj.formconfig.rules = Object.assign(obj.formconfig.rules, { [propId] :[{ required: secondItem.requiredFlag == 0 ? false :true, message: '请选择内容', trigger: 'change' }]});
              */
                secondItem.itemList.forEach(item => { radiosArr.push({ label: item.label, value: item.id }) })
                obj.formconfig.itemList.push({ type: 'select', prop: propId, label: secondItem.name, option: radiosArr, isMultiple: false })
                obj.formconfig.rules = Object.assign(obj.formconfig.rules, { [propId]: [{ required: secondItem.requiredFlag != 0, message: '请选择内容', trigger: 'change' }] })
                break
              case 3: // 多选
                // debugger
                const checkboxArr = []
                /*
              secondItem.itemList.forEach( checkboxItem => { checkboxArr.push({label:checkboxItem.label,value:checkboxItem.id}) })
              obj.formconfig.itemList.push( { type:'checkbox',prop:propId,label:secondItem.name, checkboxs:checkboxArr } )
              obj.formconfig.rules = Object.assign(obj.formconfig.rules, { [propId] :[{ type: 'array', required: secondItem.requiredFlag == 0 ? false :true, message: '请至少选择一个内容', trigger: 'change' }]});
              */
                secondItem.itemList.forEach(checkboxItem => { checkboxArr.push({ label: checkboxItem.label, value: checkboxItem.id }) })
                obj.formconfig.itemList.push({ type: 'select', prop: propId, label: secondItem.name, option: checkboxArr, isMultiple: true, isCollapseTags: true })
                obj.formconfig.rules = Object.assign(obj.formconfig.rules, { [propId]: [{ required: secondItem.requiredFlag != 0, message: '请至少选择一个内容', trigger: 'blur' }] })
                // 表单提交数据，注：如果类型是checkbox，必须foemData里边提前声明数组
                // obj.formData = Object.assign(obj.formData, {[propId]:[]})
                break
              case 4: // 时间
                obj.formconfig.itemList.push({ type: 'datapicker', prop: propId, placeholder: '请选择日期', label: secondItem.name })
                obj.formconfig.rules = Object.assign(obj.formconfig.rules, { [propId]: [{ type: 'string', required: secondItem.requiredFlag != 0, message: '请选择日期', trigger: 'change' }] })
                break
              default: // 出错 - 不在设计范围
                console.log(typeof type, type)
              // 默认代码块
            }
          })
          arr.push(obj)
        })
        this.goodsAttrData = arr
        // 编辑状态下 类目属性 回显 值
        if (this.currentPageStatus === 'edit') { this.showGoodsAttrValue(arr) }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 编辑状态下 类目属性 回显 值
    showGoodsAttrValue (arr) {
      const attrGroupList = this.infoForm.attrGroupList
      // const original = [...arr]
      // this.goodsAttrData[0].formData["value-15-20"] = "20"
      // 准备匹配值
      attrGroupList.forEach(firstItem => {
        firstItem.itemList.forEach(secondItem => {
          secondItem.matchValue = `value-${firstItem.id}-${secondItem.id}`
        })
      })
      this.goodsAttrData.forEach((firstItem, firstIndex) => {
        firstItem.formconfig.itemList.forEach(secondItem => {
          attrGroupList.forEach(attFirstItem => {
            attFirstItem.itemList.forEach(attSecondItem => {
              if (attSecondItem.matchValue == secondItem.prop) {
                // 1、文本 2、单选  3、多选  4、时间
                switch (attSecondItem.typeFlag) {
                  case '1': // 文本
                    // this.goodsAttrData[firstIndex].formData[attSecondItem.matchValue] = JSON.parse(attSecondItem.attrValueContent)
                    this.$set(this.goodsAttrData[firstIndex].formData, secondItem.prop, JSON.parse(attSecondItem.attrValueContent))
                    break
                  case '2': // 单选
                    // this.goodsAttrData[firstIndex].formData[attSecondItem.matchValue] = JSON.parse(attSecondItem.attrValueContent)
                    this.$set(this.goodsAttrData[firstIndex].formData, secondItem.prop, JSON.parse(attSecondItem.attrValueContent))
                    break
                  case '3': // 多选
                    // this.goodsAttrData[firstIndex].formData[attSecondItem.matchValue] = JSON.parse(attSecondItem.attrValueContent)
                    this.$set(this.goodsAttrData[firstIndex].formData, secondItem.prop, JSON.parse(attSecondItem.attrValueContent))
                    break
                  default: // 时间
                    // this.goodsAttrData[firstIndex].formData[attSecondItem.matchValue] = attSecondItem.attrValueContent
                    this.$set(this.goodsAttrData[firstIndex].formData, secondItem.prop, JSON.parse(attSecondItem.attrValueContent))
                }
              }
            })
          })
        })
      })
      // console.log(this.goodsAttrData[1].formData["value-15-20"])
    },
    // 选择销售属性
    onChangeGoodsSaleDataListValue (selectArr) {
      // sessionStorage.setItem('saleDataListValue', JSON.stringify(this.goodsSaleDataListValue))
      // this.skuFormConfig.attribute.splice(fatherIndex, 1)
      if (this.skuFormConfig.attribute.length >= 3) {
        console.log(this.skuFormConfig.attribute.length)
        console.log(selectArr.length)
        if (selectArr.length === 3) { selectArr.splice(3) }
        if (selectArr.length === 2) { selectArr.splice(2) }
        if (selectArr.length === 1) { selectArr.splice(1) }
      }
      this.goodsSaleDataListValue = selectArr
      const sourceAttribute = this.skuFormConfig.sourceAttribute
      const arr = []
      selectArr.forEach(item => {
        const matching = sourceAttribute.find(e => { return e.id === item })
        // console.log(matching)
        arr.push(matching)
      })
      const tempAttribute = []
      this.skuFormConfig.attribute.forEach(item => {
        if (item.id === undefined) {
          tempAttribute.push(item)
        }
      })
      this.skuFormConfig.attribute = tempAttribute
      // this.skuFormConfig.attribute = arr // SKU已选属性
      this.skuFormConfig.attribute = Array.from(new Set(this.skuFormConfig.attribute.concat(arr)))
      // ============== 初始 空数组，使用在添加新的属性  ==============
      this.skuFormConfig.inputValueArr = []
      this.skuFormConfig.inputValueArrTemp = []
      this.skuFormConfig.attribute.forEach((item, index) => {
        // this.skuFormConfig.inputValueArr.push({ name: '', item: [], itemList: [] })
        this.skuFormConfig.inputValueArr.push([])
        this.skuFormConfig.inputValueArrTemp.push('')
      })
      this.$nextTick(_ => {
        this.$refs.skuForm.init()
        console.log(this.skuFormConfig.inputValueArrTemp)
      })
    },
    onExceed () {
      selectArr.splice(selectArr.length - 1, 1)
      this.goodsSaleDataListValue = selectArr
      console.log('已经超出', this.goodsSaleDataListValue)
      console.log('已经超出', this.skuFormConfig.attribute)
    },
    // 查询指定类目的销售属性
    getGoodsSaleDataList (categoryId, goodsSpecList, goodsSpecTable) {
      const params = { categoryId }
      this.$api.categorySalesPecDetail(params).then((res) => {
        // ============== 初始SKU可选属性 ==============
        const modifySpecList = res.data
        // 修改 初始化 key 为 组件 所需要 key
        modifySpecList.forEach((e) => {
          const itemArr = []
          e.itemList.forEach((itemList) => {
            itemArr.push(itemList.content)
          })
          e.item = itemArr
        })
        this.skuFormConfig.sourceAttribute = Array.from(new Set(modifySpecList)) // SKU可选属性
        // ============== 初始 回显 已选 SKU 值  ==============
        if (goodsSpecList && goodsSpecList.length !== 0) {
          goodsSpecList = goodsSpecList.sort(function (a, b) { return a.id - b.id })
          goodsSpecList.forEach(firstItem => {
            const itemArr = []
            firstItem.itemList.forEach(secondItem => {
              itemArr.push(secondItem.content)
            })
            firstItem.item = itemArr
          })
          this.skuFormConfig.attribute = goodsSpecList
          const tempSourceAttribute = Array.from(new Set(this.skuFormConfig.sourceAttribute.concat(goodsSpecList).filter(Boolean)))

          /**
           * 删除数组对象中重复的对象
           * arr: 源数组   filterField: 需要删除的重复字段，注意是字符串类型
           * 返回一个过滤好的，没有重复该字段filterField的数组
           * */
          const filterArrObj = (arr,filterField) =>{
            let newArr = arr.reduce((pre,cur) => pre.some(item => item[filterField] == cur[filterField]) ?
                pre : [...pre,cur],[])
            return newArr
          }
          this.skuFormConfig.sourceAttribute = filterArrObj(tempSourceAttribute,'name')
          console.log(this.skuFormConfig)
          // const echoSpecList = []
        }

        if (goodsSpecTable && goodsSpecTable.length !== 0) {
          goodsSpecTable.forEach(item => {
            const arr = []
            arr.push(item.firstGoodsSpecItemContent)
            if (item.secondGoodsSpecItemContent) { arr.push(item.secondGoodsSpecItemContent) }
            if (item.thirdGoodsSpecItemContent) { arr.push(item.thirdGoodsSpecItemContent) }
            item.sku = arr.join(';')
            item.status = item.status.toString()
          })
          this.skuFormConfig.sku = Array.from(new Set(goodsSpecTable))
          // 还原数据时，SKU组件将 ID 过滤掉，先将 数据缓存到本地，提交数据时使用
          sessionStorage.setItem('skuFormConfigSku', JSON.stringify(goodsSpecTable))
        }
        /*
        // SKU已选属性 编辑模式下使用
        if (this.currentPageStatus !== 'add') {
          this.skuFormConfig.attribute = Array.from(new Set(selectedSku)) // SKU已选属性
          this.skuFormConfig.sku = Array.from(new Set(modifySpecTable)) // SKU数据
          this.$nextTick(_ => {
            this.$refs.skuForm.init()
            // 提交数据时使用
            sessionStorage.setItem('skuFormConfigSku', JSON.stringify(modifySpecTable))
          })
        }
        */
        // ============== 初始 空数组，使用在添加新的属性  ==============
        this.skuFormConfig.attribute.forEach((item, index) => {
          this.skuFormConfig.inputValueArr.push([])
          this.skuFormConfig.inputValueArrTemp.push('')
        })

        // console.log(this.skuFormConfig)
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取 品牌 列表
    getBrandList (categoryId) {
      const params = { pageNo: 1, pageSize: 999, categoryId }
      this.$api.brandCommList(params).then((res) => {
        this.brandList = res.data.list
        this.brandList.push({
          id: '-1',
          name: '其它'
        })
        console.log(this.brandList)
      }).catch((err) => {
        console.log(err)
      })
    },
    // 搜索 选择 类目
    onChangeCategory (val) {
      console.log(val)
      // this.search.classId = val[val.length -1]
      // console.log(val, this.search.classId)
    },
    // 修改 回显 classId
    onChangeEditClassId (categoryIdInfo, categoryInfoList) {
      // debugger
      let categoryId
      let categoryArrStr = ''
      if (typeof categoryIdInfo === 'string') {
        categoryId = categoryIdInfo
      } else {
        categoryId = categoryIdInfo[categoryIdInfo.length - 1]
      }
      const categoryList = this.categoryList
      if (categoryList.length < 0) { console.log('categoryList没到位！', categoryList) }
      const arr = []
      categoryList.forEach((firstItem, firstIndex) => {
        if (firstItem.id === categoryId) {
          console.log(firstItem.label)
          categoryArrStr = firstItem.label
          arr.push(firstItem.id)
          return
        }
        if (firstItem.children) {
          firstItem.children.forEach((secondItem, secondIndex) => {
            if (secondItem.id === categoryId) {
              categoryArrStr = `${firstItem.label} > ${secondItem.label}`
              arr.push(firstItem.id)
              arr.push(secondItem.id)
              return
            }
            if (secondItem.children) {
              secondItem.children.forEach((thirdItem, thirdIndex) => {
                if (thirdItem.id === categoryId) {
                  categoryArrStr = `${firstItem.label} > ${secondItem.label} > ${thirdItem.label}`
                  arr.push(firstItem.id)
                  arr.push(secondItem.id)
                  arr.push(thirdItem.id)
                  return
                }
              }) // third end
            }
          }) // second end
        }
      }) // first end

      if (categoryArrStr.length == '' || categoryArrStr.length < 0) {
        if (categoryInfoList) {
          categoryInfoList.reverse()
          const tempArr = []
          categoryInfoList.forEach(item => {
            tempArr.push(item.categoryName)
          })
          categoryArrStr = tempArr.join(' > ')
          console.log(categoryArrStr)
        } else {
          console.log('还没选择商品分类1', categoryArrStr)
          this.$alert('还没选择商品分类', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              console.log(action)
              this.toOtherPages('goodsCategoryEdit')
            }
          })
        }
      }
      this.categoryArrStr = categoryArrStr
    },
    // 生成sku编码
    getSkuNo (id) {
      // 主键id请求
      const params = { id }
      this.$api.gkuNoByGoodId(params).then((res) => {
        this.maxSkuNo = Number(res.data) // 获取 的 skuNo 转数字，方便后面使用可以自增
      }).catch((err) => {
        console.log(err)
      })
    },
    // 表单规则验证
    verificationData () {
      // 'formAttr'+item.id
      // console.log("表单规则验证 - verificationData - goodsAttrData", this.goodsAttrData)
      this.$refs['infoForm'].validate((valid) => {
        if (valid) {
          this.goodsAttrData.forEach(item => {
            const formName = 'formAttr' + item.id
            this.$refs[formName][0].submitForm('ruleForm')
          })
          this.$refs.skuForm.validate(valid => {
            if (valid) {
              // this.$message.success('skuForm验证通过')
              // 图片信息检查
              if (this.infoForm.imageList.length !== 0) {
                if (this.formFiledDataState) {
                  this.submitDate()
                } else {
                  this.$message.warning('请完善类目属性再提交！')
                }
              } else {
                this.$message.warning('请完善图片信息再提交！')
              }
            } else {
              // this.$message.warning('skuForm验证失败')
              return
            }
          })
        } else {
          this.$message.warning('请完善信息再提交！')
          console.log('error submit!!')
          return false
        }
      })
    },
    // 提交 数据
    submitDate () {
      const params = Object.assign({}, this.infoForm)
      const formFiledData = Object.assign({}, this.formFiledData) // 接受表单组件的数据
      const attrListTemp = [] 	// 商品属性组列表
      // const goodsAttrDataList = this.goodsAttrDataList // 类目商品属性库列表
      const goods_typeFindObj = this.dictionaries.goods_type.find(e => { return e.dictName === this.infoForm.goodsType })
      if (goods_typeFindObj) { params.goodsType = Number(goods_typeFindObj.dictId) }
      const statusFindObj = this.dictionaries.sale_status.find(e => { return e.dictName === this.infoForm.status })
      if (statusFindObj) { params.status = statusFindObj.dictId }
      /*
      // 接受 表单组件 的数据 整理
      attrGroupId:1,//	是	int	属性组id
      attrId:1,	//是	int	属性id
      goodsAttrItemId:1,	//否	int	属性值id（下拉）
      attrValueContent:1,//	否	String	属性值内容（日期、填空）
      */
      for (const item in formFiledData) {
        const itemTemp = item.split('-')
        const objTemp = { attrGroupId: Number(itemTemp[1]), attrId: Number(itemTemp[2]), goodsAttrItemId: Number(formFiledData[item]), attrValueContent: JSON.stringify(formFiledData[item]) }
        // console.log(itemTemp)
        attrListTemp.push(objTemp)
      }
      params.attrList = attrListTemp // 商品属性组列表
      // 规格列表
      const skuFormConfigAttribute = this.skuFormConfig.attribute
      skuFormConfigAttribute.forEach(firstItem => {
        firstItem.sort = firstItem.id ? Number(firstItem.id) : 1
        firstItem.itemList.forEach(secondItem => {
          secondItem.sort = secondItem.id ? Number(secondItem.id) : 1
        })
      })

      // 合并新添加的规格值
      skuFormConfigAttribute.forEach((firstItem, firstIndex) => {
        const inputValueArr = this.skuFormConfig.inputValueArr
        firstItem.itemList = firstItem.itemList.concat(inputValueArr[firstIndex]).filter(Boolean)
        firstItem.itemList = Array.from(new Set(firstItem.itemList))
      })
      params.specList = skuFormConfigAttribute

      const tempAttribute = this.skuFormConfig.attribute
      const skuFormConfigSku = this.skuFormConfig.sku
      skuFormConfigSku.forEach(item => { item.sku = item.sku.split(';') })
      skuFormConfigSku.forEach((firstItem, firstIndex) => {
        const attributeLength = skuFormConfigAttribute.length
        firstItem.sort = 1
        firstItem.sku.forEach((secondItem, secondIndex) => {
          switch (attributeLength) {
            case 1:
              firstItem.firstGoodsSpecName = tempAttribute[0].name
              firstItem.firstGoodsSpecItemContent = firstItem.sku[0]
              break
            case 2:
              firstItem.firstGoodsSpecName = tempAttribute[0].name
              firstItem.secondGoodsSpecName = tempAttribute[1].name
              firstItem.firstGoodsSpecItemContent = firstItem.sku[0]
              firstItem.secondGoodsSpecItemContent = firstItem.sku[1]
              break
            case 3:
              firstItem.firstGoodsSpecName = tempAttribute[0].name
              firstItem.secondGoodsSpecName = tempAttribute[1].name
              firstItem.thirdGoodsSpecName = tempAttribute[2].name
              firstItem.firstGoodsSpecItemContent = firstItem.sku[0]
              firstItem.secondGoodsSpecItemContent = firstItem.sku[1]
              firstItem.thirdGoodsSpecItemContent = firstItem.sku[2]
              break
          }
        })
      })
      const currentPageStatus = this.currentPageStatus
      // 编辑时，给SKU添加ID   获取 缓存 数据 匹配 ID
      if (currentPageStatus === 'edit') {
        // console.log("页面状态", typeof currentPageStatus, currentPageStatus)
      // const skuFormConfigSkuLs = Array.from(new Set(JSON.parse(sessionStorage.getItem('skuFormConfigSku'))))
        const skuFormConfigSkuls = JSON.parse(sessionStorage.getItem('skuFormConfigSku'))
        skuFormConfigSku.forEach(item => {
          skuFormConfigSkuls.forEach(itemLs => {
            if (item.skuNo === itemLs.skuNo) {
              item.id = itemLs.id
            }
          })
        })
      }

      // 添加模式下 添加 skuNo 编号
      if (currentPageStatus === 'add') {
        skuFormConfigSku.forEach((item, index) => {
          item.skuNo = this.maxSkuNo
          item.skuNo = item.skuNo < 10 ? '0' + item.skuNo.toString() : item.skuNo.toString()
          this.maxSkuNo++
        })
      }

      // 复查 skuNo
      skuFormConfigSku.forEach((item, index) => {
        if (item.skuNo === '' || item.skuNo === undefined || item.skuNo === null) {
          // 生成sku编码
          const newSkuNo = this.maxSkuNo
          item.skuNo = newSkuNo < 10 ? '0' + newSkuNo.toString() : newSkuNo.toString()
          this.maxSkuNo++
        }
        delete item.sku
      })

      params.skuList = skuFormConfigSku
      // 图片列表 ，设置第一张图为主图
      if (params.imageList && params.imageList[0]) { params.imageList[0].mainFlag = 1 }
      // 删除多余参数属性
      delete params.maxPrice
      delete params.minPrice
      console.log('提交数据', params)
      // return
      if (this.currentPageStatus === 'add') {
        // 添加
        this.$api.goodsAdd(params).then((res) => {
          if (res.code === 0) {
            // this.$message({ type: 'success', message: '添加商品成功!' })
            this.$notify({
              title: '成功',
              message: '添加商品成功!',
              type: 'success',
              duration: 3000
            })
            this.toOtherPages('goodsList')
          }
        }).catch((err) => {
          console.log(err)
        })
      } else {
        // 编辑
        delete params.attrGroupList
        delete params.categoryInfo
        delete params.goodsNo
        this.$api.goodsEdit(params).then((res) => {
          if (res.code === 0) {
            // this.$message({ type: 'success', message: '添加商品成功!' })
            this.$notify({
              title: '成功',
              message: '修改商品成功!',
              type: 'success',
              duration: 3000
            })
            this.toOtherPages('goodsList')
          }
        }).catch((err) => {
          console.log(err)
          this.initialization() // 初始化 信息
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.div1 {
  margin-left: -16px;
  background: url(../../assets/breadcrumb2.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}
.div2 {
  margin-left: -16px;
  background: url(../../assets/breadcrumb1.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #fff;
}
// .content{color: #333333!important;}
//删除全页面按钮边框
.el-button { border: none; }
.image-text-form{
  .el-form{
    .el-form-item{
      &:first-child{
        .el-form-item__label{
          &:before{
            color: #ff0000;
            content: "*";
          }
        }
      }
    }
  }
}
.goods-category-edit {
  .edit-btn {
    background-color: #e3edff;
    color: #4168e7;
    font-size: 14px;
    text-align: center;
    width: 44px;
    height: 24px;
    line-height: 24px;
    border-radius: 12px;
    padding: 3px 8px;
    margin-left: 10px;
    cursor: pointer;
  }
}
.status-box {
  font-size: 16px;
  height: 40px;
  line-height: 40px;
  .list,
  .right {
    float: left;
  }
  .list {
    width: 100px;
    text-align: center;
  }
  .right {
    padding-top: 15px;
    width: calc(100% - 100px);
    .el-radio__label {
      font-size: 16px;
    }
  }
}
.bottom-but {
  margin-top: -20px;
  text-align: center;
  .el-button {
    width: 220px;
    height: 48px;
    border-radius: 4px;
    font-size: 18px;
  }
  .el-button + .el-button {
    margin-left: 32px;
  }
}
.el-select{
  border-left: 1px solid #d8dce5; border-right: 1px solid #d8dce5;border-radius: 5px;
  input[type="text"], input[type="number"]{border-radius: 0; border-left: none; border-right: none;}
}
.attr{
  margin-top: 0;
}
.content{
  padding-bottom:10px!important;
}
</style>
